const coupon = require('../../models/good/coupon');
class CouponService {
    static async getCouponList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            const query = {
                ...(data?.name && { name: { $regex: data.name, $options: 'i' } }),
                ...(data?.isActive && { isActive: data.isActive }), // 状态，1: 未使用，2: 已使用，3: 已过期

                ...(data?.startDate && { startDate: { $gte: data.startDate } }),
                ...(data?.endDate && { endDate: { $lte: data.endDate } }),
                ...(data?.minPurchase && { minPurchase: { $gte: data.minPurchase } }), // 最低订单金额
            };
            const skip = (pageNum - 1) * pageSize;
            const limit = pageSize;
            const total = await coupon.countDocuments(query);
            const couponList = await coupon.find(query).skip(skip).limit(limit).populate('applicableCategories').populate('applicableProducts').lean();
            return {
                total,
                page: +pageNum,
                totalPages: Math.ceil(total / pageSize),
                list: couponList,
            };
        } catch (error) {
            throw new Error('获取优惠券列表失败: ' + error.message);
        }
    }
    static async getCouponById(couponId) {
        return await coupon.findById(couponId).populate("applicableCategories").populate("applicableProducts").lean();
    }
    static async createCoupon(couponData) {
        return await coupon.create(couponData);
    }
    static async updateCoupon(couponId, couponData) {
        return await coupon.findByIdAndUpdate(couponId, { $set: couponData }, { new: true });
    }
    static async deleteCoupon(couponId) {
        return await coupon.findByIdAndDelete(couponId);
    }
}
module.exports = CouponService;
